package cn.gwm.flink.streaming.config;

import cn.gwm.flink.streaming.business.ModuleConfData;
import cn.gwm.flink.streaming.dws.reservecharge.ChargePrice;
import cn.gwm.utils.GlobalConfigUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author Liu.Nanfang
 * @Date 2023/3/28 11:43
 * @Description 单例全局定时任务
 */
@Slf4j
public class GlobalConfigSingleton {

    /**
     * 定时执行时间 2 小时
     */
    private static final long MODULE_PERIOD = 2;
    /**
     * 定时电价信息定时执行时间 1 小时
     */
    private static final long CHARGE_PRICE_PERIOD = 1;
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private static GlobalConfigSingleton instance;
    /**
     * 功能服务配置
     */
    private static ModuleConfData moduleConfData;

    private GlobalConfigSingleton() {
        init();
    }

    public static synchronized GlobalConfigSingleton getInstance() {
        if (instance == null) {
            synchronized (GlobalConfigSingleton.class) {
                if (instance == null) {
                    instance = new GlobalConfigSingleton();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化
     */
    public void init() {
        moduleConfData = loadGlobalConfigData();
        scheduleConfigUpdate();
        scheduleChargePriceConfigUpdate();
    }

    /**
     * 调度任务
     */
    private void scheduleConfigUpdate() {
        scheduler.scheduleAtFixedRate(() -> {
            log.info("newScheduledThreadPool load  moduleConfig data \n");
            moduleConfData = loadGlobalConfigData();
        }, 0, MODULE_PERIOD, TimeUnit.HOURS);
    }

    private void scheduleChargePriceConfigUpdate() {
        ChargePrice chargePrice = ChargePrice.getInstance();
        scheduler.scheduleAtFixedRate(() -> chargePrice.updateChargePriceInfoList(), 0, CHARGE_PRICE_PERIOD, TimeUnit.HOURS);
    }

    private ModuleConfData loadGlobalConfigData() {
        List<ModuleConfData.ModuleConf> list = GlobalConfigUtil.requestModuleConfigList();
        if (list.size() > 0) {
            ModuleConfData newModuleConfData = new ModuleConfData();
            newModuleConfData.setGlobalModuleConfigData(list);
            return newModuleConfData;
        }
        return moduleConfData;
    }

    public ModuleConfData getGlobalModuleConfigData() {
        return moduleConfData;
    }


}
